//
//  AddNewItemViewController.m
//  FMS
//
//  Created by Steven on 10/14/13.
//  Copyright (c) 2013 QGSVN. All rights reserved.
//

#import "AddNewItemViewController.h"
#import "BuildingMgmtViewController.h"
#import "DetailedItemViewController.h"

@interface AddNewItemViewController ()

@end

//@implementation UITextField (CustomTextField)
//
//- (void) dealloc {
//    [self setDelegate:nil];
//}
//@end

@implementation AddNewItemViewController
@synthesize delegate;
@synthesize isEdit;
@synthesize itemDetailedDict;
@synthesize parent;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil itemType:(int)_itemType parent:(id)_parent
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        dictLanguage = [ApplicationDelegate.arrayLanguage objectAtIndex:0];
        itemType = _itemType;
        parent = _parent;
    }
    return self;
}

- (void) dealloc {
    NSLog(@"%@ dealloc",self);
    delegate = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];
}

- (NSMutableDictionary*) setObjectValueToDictionary:(NSMutableDictionary*)_dict objectType:(int)_objectType objectValue:(NSString*)objectValue itemType:(int)_itemType {
    if (_itemType == Building_Type) {
        switch (_objectType) {
            case filter_service:
                [_dict setObject:objectValue forKey:@"service"];
                break;
            case filter_camp:
                [_dict setObject:objectValue forKey:@"camp"];
                break;
            case filter_unit:
                [_dict setObject:objectValue forKey:@"unit"];
                break;
            case filter_building:
                [_dict setObject:objectValue forKey:@"building"];
                break;
            case filter_floor:
                [_dict setObject:objectValue forKey:@"floor"];
                break;
            case filter_office:
                [_dict setObject:objectValue forKey:@"type"];
                break;
            case filter_normal_ops:
                [_dict setObject:objectValue forKey:@"normal_ops"];
                break;
            case b_room_name:
                [_dict setObject:objectValue forKey:@"item_name"];
                break;
            case b_square_metres:
                [_dict setObject:objectValue forKey:@"square_metres"];
                break;
            case b_date_of_completion:
                [_dict setObject:objectValue forKey:@"date_of_completion"];
                break;
            case b_warranty_date_exp:
                [_dict setObject:objectValue forKey:@"date_of_exp"];
                break;
            case b_construction_cost:
                [_dict setObject:objectValue forKey:@"construction_cost"];
                break;
            case b_age:
                [_dict setObject:objectValue forKey:@"age"];
                break;
            case b_cost_incurred_previous_year:
                [_dict setObject:objectValue forKey:@"cost_incurred_previous_year"];
                break;
            case b_cost_incurred_current_year:
                [_dict setObject:objectValue forKey:@"cost_incurred_current_year"];
                break;
            case b_date_of_demolition:
                [_dict setObject:objectValue forKey:@"date_of_demolition"];
                break;
            case b_demolition_reason:
                [_dict setObject:objectValue forKey:@"demolition_reason"];
                break;
            case filter_contractor:
                [_dict setObject:objectValue forKey:@"contractor"];
                break;
            default:
                break;
        }
    }
    else {
        switch (_objectType) {
            case f_equipment_id:
                [_dict setObject:objectValue forKey:@"item_name"];
                break;
            case filter_service:
                [_dict setObject:objectValue forKey:@"service"];
                break;
            case filter_camp:
                [_dict setObject:objectValue forKey:@"camp"];
                break;
            case filter_unit:
                [_dict setObject:objectValue forKey:@"unit"];
                break;
            case filter_building:
                [_dict setObject:objectValue forKey:@"building"];
                break;
            case filter_location:
                [_dict setObject:objectValue forKey:@"building"];
                [_dict setObject:[NSNumber numberWithInt:1] forKey:@"isOther"];
                [_dict setObject:@"0" forKey:@"floor"];
                [_dict setObject:@"0" forKey:@"room"];
                break;
            case filter_floor:
                [_dict setObject:objectValue forKey:@"floor"];
                break;
            case filter_room:
                [_dict setObject:objectValue forKey:@"room"];
                break;
            case filter_system:
                [_dict setObject:objectValue forKey:@"system"];
                break;
            case filter_description:
                [_dict setObject:objectValue forKey:@"description"];
                break;
            case f_brand:
                [_dict setObject:objectValue forKey:@"brand"];
                break;
            case f_serial_no:
                [_dict setObject:objectValue forKey:@"serial_no"];
                break;
            case f_make_model:
                [_dict setObject:objectValue forKey:@"make_model"];
                break;
            case f_capacity:
                [_dict setObject:objectValue forKey:@"capacity"];
                break;
            case f_expiry_date:
                [_dict setObject:objectValue forKey:@"date_of_exp"];
                break;
            case f_manufacture_detail:
                [_dict setObject:objectValue forKey:@"manufacturer_detail"];
                break;
            case f_agent_detail:
                [_dict setObject:objectValue forKey:@"agent_detail"];
                break;
            case filter_normal_ops:
                [_dict setObject:objectValue forKey:@"normal_ops"];
                break;
            case f_capital_cost:
                [_dict setObject:objectValue forKey:@"capital_cost"];
                break;
            case f_date_of_installation:
                [_dict setObject:objectValue forKey:@"date_of_installation"];
                break;
            case f_age:
                [_dict setObject:objectValue forKey:@"age"];
                break;
            case f_amp_frequency:
                [_dict setObject:objectValue forKey:@"amp_frequency"];
                break;
            case f_amp_budciet:
                [_dict setObject:objectValue forKey:@"amp_budciet"];
                break;
            case f_cost_incurred_previous_year:
                [_dict setObject:objectValue forKey:@"cost_incurred_previous_year"];
                break;
            case f_cost_incurred_current_year:
                [_dict setObject:objectValue forKey:@"cost_incurred_current_year"];
                break;
            case f_date_of_condemnation:
                [_dict setObject:objectValue forKey:@"date_of_condemnation"];
                break;
            case f_condemnation_reason:
                [_dict setObject:objectValue forKey:@"condemnation_reason"];
                break;
            case filter_contractor:
                [_dict setObject:objectValue forKey:@"contractor"];
                break;
            default:
                break;
        }
    }
    return _dict;
}

- (IBAction)backPreviousView:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)saveItem:(id)sender {
    [myTextField resignFirstResponder];
    
    UIAlertView *dialog;
    
    //add new field dateUpdatedCost for FMS-390
    NSDate *now = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss a"];
    NSString *dateUpdatedCost = [dateFormatter stringFromDate:now];
    
    if (itemType == Building_Type) {
        //check validate input data
#ifndef vDEBUG
        for (int i=0;i < [mainArray count];i++) {
            NSMutableDictionary *tmpDict = [mainArray objectAtIndex:i];
            int objectType = [[tmpDict objectForKey:@"objectType"] intValue];
            NSString *objectValue = [tmpDict objectForKey:@"objectValue"];
            
            //check validate input data
            switch (objectType) {
                case b_room_name:
                    if ([objectValue isEqualToString:@""] || objectValue == nil) {
                        dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"building-mgmt.add-new-room.room-name-not-blank"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                        [dialog show];
                        return;
                    }
                    break;
                case filter_service:
                    if ([objectValue isEqualToString:[dictLanguage objectForKey:@"filter.select-service"]]) {
                        dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"building-mgmt.add-new-room.require-select-service"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                        [dialog show];
                        return;
                    }
                    break;
                case filter_camp:
                    if ([objectValue isEqualToString:[dictLanguage objectForKey:@"filter.select-camp"]]) {
                        dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"building-mgmt.add-new-room.require-select-camp"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                        [dialog show];
                        return;
                    }
                    break;
                case filter_unit:
                    if ([objectValue isEqualToString:[dictLanguage objectForKey:@"filter.select-unit"]]) {
                        dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"building-mgmt.add-new-room.require-select-unit"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                        [dialog show];
                        return;
                    }
                    break;
                case filter_building:
                    if ([objectValue isEqualToString:[dictLanguage objectForKey:@"filter.select-building"]]) {
                        dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"building-mgmt.add-new-room.require-select-building"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                        [dialog show];
                        return;
                    }
                    break;
                case filter_floor:
                    if ([objectValue isEqualToString:[dictLanguage objectForKey:@"filter.select-floor"]]) {
                        dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"building-mgmt.add-new-room.require-select-floor"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                        [dialog show];
                        return;
                    }
                    break;
                case filter_office:
                    if ([objectValue isEqualToString:[dictLanguage objectForKey:@"schedule.title-select"]]) {
                        dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"building-mgmt.add-new-room.require-select-type"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                        [dialog show];
                        return;
                    }
                    break;
                case filter_normal_ops:
                    if ([objectValue isEqualToString:[dictLanguage objectForKey:@"schedule.title-select"]]) {
                        dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"building-mgmt.add-new-room.require-select-normal-ops-critical"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                        [dialog show];
                        return;
                    }
                    break;
                case filter_contractor:
//                    if ([objectValue isEqualToString:[dictLanguage objectForKey:@"maintenance-mgmt.select-contractor.button-title"]]) {
                    if (contratorId == nil || [contratorId isEqualToString:@"0"]) {
                        dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"building-mgmt.add-new-room.require-select-contractor"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                        [dialog show];
                        return;
                    }
                    break;
//                case b_date_of_completion:
//                    if (![objectValue isEqualToString:@""] && objectValue != nil) {
//                        isValidDate = YES;
//                    }
//                    break;
                case b_age:
                    currentAge = [objectValue intValue];
                    break;
                default:
                    break;
            }
        }
#endif
        if (currentAge != previousAge) {
            previousAge = currentAge;
            //display dialog to inform convert the date of completion
            dialog = [[UIAlertView alloc] initWithTitle:nil message:[dictLanguage objectForKey:@"building-mgmt.add-new-room.convert-completion-date"] delegate:self cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
            dialog.tag = 2;
        }
        else {
            if (!isEdit) {
                //split data
                NSMutableDictionary *inputDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:BuildingMgmtDoc,@"Table",[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]],@"dateUpdated", [NSNumber numberWithBool:YES],@"status",contratorId,@"contractorId",dateUpdatedCost,@"dateUpdatedCost",nil];
                
                for (int i=0;i < [mainArray count];i++) {
                    NSMutableDictionary *tmpDict = [mainArray objectAtIndex:i];
                    int objectType = [[tmpDict objectForKey:@"objectType"] intValue];
                    NSString *objectValue = [tmpDict objectForKey:@"objectValue"];
                    
                    [self setObjectValueToDictionary:inputDict objectType:objectType objectValue:objectValue itemType:itemType];
                }
                
                if ([CouchBaseLiteLib addNewRoom:[CouchBaseLiteLib sharedCouchBaseLite].database inputDict:inputDict]) {
                    dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.add-new.success"] message:[dictLanguage objectForKey:@"building-mgmt.add-new-room.success"] delegate:self cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                }
                else {
                    dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.add-new.failed"] message:[dictLanguage objectForKey:@"building-mgmt.add-new-room.fail"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                }
            }
            else {
                //get document
                CBLDocument *document = [CouchBaseLiteLib getDocumentById:[itemDetailedDict objectForKey:@"_id"]];
                NSMutableDictionary *newDict = [itemDetailedDict mutableCopy];
                
                for (int i=0;i < [mainArray count];i++) {
                    NSMutableDictionary *tmpDict = [mainArray objectAtIndex:i];
                    int objectType = [[tmpDict objectForKey:@"objectType"] intValue];
                    NSString *objectValue = [tmpDict objectForKey:@"objectValue"];
                    
                    [self setObjectValueToDictionary:newDict objectType:objectType objectValue:objectValue itemType:itemType];
                }
                
                if (contratorId != nil)
                    [newDict setObject:contratorId forKey:@"contractorId"];
                
                if ([CouchBaseLiteLib updateRoom:document inputDict:newDict]) {
                    CBLDocument *document = [CouchBaseLiteLib getDocumentById:[itemDetailedDict objectForKey:@"_id"]];
                    itemDetailedDict = (NSMutableDictionary*)document.properties;
                    
                    dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.edit.success"] message:[dictLanguage objectForKey:@"building-mgmt.edit-room.success"] delegate:self cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                    dialog.tag = 1;
                }
                else {
                    dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.edit.failed"] message:[dictLanguage objectForKey:@"building-mgmt.edit-room.fail"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                }
            }
        }
    }
    else {
#ifndef vDEBUG
        //check validate input data
        for (int i=0;i < [mainArray count];i++) {
            NSMutableDictionary *tmpDict = [mainArray objectAtIndex:i];
            int objectType = [[tmpDict objectForKey:@"objectType"] intValue];
            NSString *objectValue = [tmpDict objectForKey:@"objectValue"];
            
            //check validate input data
            switch (objectType) {
                case f_equipment_id:
                    if ([objectValue isEqualToString:@""] || objectValue == nil) {
                        dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"building-mgmt.add-new-facility.facility-name-not-blank"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                        [dialog show];
                        return;
                    }
                    break;
                case filter_service:
                    if ([objectValue isEqualToString:[dictLanguage objectForKey:@"filter.select-service"]]) {
                        dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"building-mgmt.add-new-room.require-select-service"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                        [dialog show];
                        return;
                    }
                    break;
                case filter_camp:
                    if ([objectValue isEqualToString:[dictLanguage objectForKey:@"filter.select-camp"]]) {
                        dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"building-mgmt.add-new-room.require-select-camp"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                        [dialog show];
                        return;
                    }
                    break;
                case filter_unit:
                    if ([objectValue isEqualToString:[dictLanguage objectForKey:@"filter.select-unit"]]) {
                        dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"building-mgmt.add-new-room.require-select-unit"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                        [dialog show];
                        return;
                    }
                    break;
                case filter_building:
                    if ([objectValue isEqualToString:[dictLanguage objectForKey:@"filter.select-building"]]) {
                        dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"building-mgmt.add-new-room.require-select-building"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                        [dialog show];
                        return;
                    }
                    break;
                case filter_floor:
                    if ([objectValue isEqualToString:[dictLanguage objectForKey:@"filter.select-floor"]]) {
                        dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"building-mgmt.add-new-room.require-select-floor"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                        [dialog show];
                        return;
                    }
                    break;
                case filter_room:
                    if ([objectValue isEqualToString:[dictLanguage objectForKey:@"filter.select-room"]]) {
                        dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"facility-mgmt.add-new-facility.require-select-room"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                        [dialog show];
                        return;
                    }
                    break;
                case filter_system:
                    if ([objectValue isEqualToString:[dictLanguage objectForKey:@"filter.select-system"]]) {
                        dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"facility-mgmt.add-new-facility.require-select-system"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                        [dialog show];
                        return;
                    }
                    break;
                case filter_description:
                    if ([objectValue isEqualToString:[dictLanguage objectForKey:@"filter.select-description"]]) {
                        dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"facility-mgmt.add-new-facility.require-select-description"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                        [dialog show];
                        return;
                    }
                    break;
                case filter_normal_ops:
                    if ([objectValue isEqualToString:[dictLanguage objectForKey:@"schedule.title-select"]]) {
                        dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"building-mgmt.add-new-room.require-select-normal-ops-critical"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                        [dialog show];
                        return;
                    }
                    break;
                case filter_contractor:
//                    if ([objectValue isEqualToString:[dictLanguage objectForKey:@"maintenance-mgmt.select-contractor.button-title"]]) {
                    if (contratorId == nil || [contratorId isEqualToString:@"0"]) {
                        dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"building-mgmt.add-new-room.require-select-contractor"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                        [dialog show];
                        return;
                    }
                    break;
//                case f_date_of_installation:
//                    if (![objectValue isEqualToString:@""] && objectValue != nil) {
//                        isValidDate = YES;
//                    }
//                    break;
                case f_age:
                    currentAge = [objectValue intValue];
                    break;
                default:
                    break;
            }
        }
#endif
        if (currentAge != previousAge) {
            previousAge = currentAge;
            //display dialog to inform convert the date of completion
            dialog = [[UIAlertView alloc] initWithTitle:nil message:[dictLanguage objectForKey:@"building-mgmt.add-new-equipment.convert-installation-date"] delegate:self cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
            dialog.tag = 2;
        }
        else {
            if (!isEdit) {
                NSMutableDictionary *inputDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:FacilityMgmtDoc,@"Table",[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]],@"dateUpdated", [NSNumber numberWithBool:YES],@"status",contratorId,@"contractorId",dateUpdatedCost,@"dateUpdatedCost",nil];
                
                for (int i=0;i < [mainArray count];i++) {
                    NSMutableDictionary *tmpDict = [mainArray objectAtIndex:i];
                    int objectType = [[tmpDict objectForKey:@"objectType"] intValue];
                    NSString *objectValue = [tmpDict objectForKey:@"objectValue"];
                    
                    [self setObjectValueToDictionary:inputDict objectType:objectType objectValue:objectValue itemType:itemType];
                }
                
                if ([CouchBaseLiteLib addNewEquipment:[CouchBaseLiteLib sharedCouchBaseLite].database inputDict:inputDict]) {
                    dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.add-new.success"] message:[dictLanguage objectForKey:@"facility.add-new-equipment.success"] delegate:self cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                }
                else {
                    dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.add-new.failed"] message:[dictLanguage objectForKey:@"facility.add-new-equipment.fail"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                }
            }
            else {
                //get document
                CBLDocument *document = [CouchBaseLiteLib getDocumentById:[itemDetailedDict objectForKey:@"_id"]];
                NSMutableDictionary *newDict = [itemDetailedDict mutableCopy];
                
                for (int i=0;i < [mainArray count];i++) {
                    NSMutableDictionary *tmpDict = [mainArray objectAtIndex:i];
                    int objectType = [[tmpDict objectForKey:@"objectType"] intValue];
                    NSString *objectValue = [tmpDict objectForKey:@"objectValue"];
                    
                    [self setObjectValueToDictionary:newDict objectType:objectType objectValue:objectValue itemType:itemType];
                }
                
                //            [newDict setObject:mainArray forKey:@"itemData"];
                if (contratorId != nil)
                    [newDict setObject:contratorId forKey:@"contractorId"];
                
                if ([CouchBaseLiteLib updateRoom:document inputDict:newDict]) {
                    CBLDocument *document = [CouchBaseLiteLib getDocumentById:[itemDetailedDict objectForKey:@"_id"]];
                    itemDetailedDict = (NSMutableDictionary*)document.properties;
                    
                    dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.edit.success"] message:[dictLanguage objectForKey:@"facility.edit-equipment.success"] delegate:self cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                }
                else {
                    dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.edit.failed"] message:[dictLanguage objectForKey:@"building-mgmt.edit-room.fail"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                }
            }
        }
    }
    [dialog show];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    _mainTableView.separatorColor = [UIColor clearColor];
    
    _mainTableView.allowsSelection = NO;
    
    mainArray = [NSMutableArray arrayWithCapacity:1];
    
    buildingId = @"0";
    serviceId = @"0";
    campId = @"0";
    unitId = @"0";
    floorId = @"0";
    systemId = @"0";
    descriptionId = @"0";
    contratorId = @"0";
    roomId = @"0";
    
    filterDictValue = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%d",0],@"service",[NSString stringWithFormat:@"%d",0],@"camp",[NSString stringWithFormat:@"%d",0],@"unit",[NSString stringWithFormat:@"%d",0],@"building",[NSString stringWithFormat:@"%d",0],@"floor",[NSString stringWithFormat:@"%d",0],@"room", nil];
    
    if (itemType == Building_Type){
        _lbMainTitle.text = [dictLanguage objectForKey:@"building-mgmt.add-new-room.main-title"];
        //there are 16 rows
        NSString *lbTitle[] = {
            [dictLanguage objectForKey:@"building-mgmt.add-new-room.room-name"],
            [dictLanguage objectForKey:@"schedule.title-service"],
            [dictLanguage objectForKey:@"schedule.title-camp"],
            [dictLanguage objectForKey:@"schedule.title-unit"],
            [dictLanguage objectForKey:@"schedule.title-building"],
            [dictLanguage objectForKey:@"schedule.title-floor"],
            [dictLanguage objectForKey:@"building-mgmt.add-new-room.type"],
            [dictLanguage objectForKey:@"building-mgmt.add-new-room.normal-ops-critical"],
            [dictLanguage objectForKey:@"building-mgmt.add-new-room.square-metres"],
            [dictLanguage objectForKey:@"building-mgmt.add-new-room.date-of-completion"],
            [dictLanguage objectForKey:@"building-mgmt.add-new-room.warranty-date-exp"],
            [dictLanguage objectForKey:@"building-mgmt.add-new-room.construction-cost"],
            [dictLanguage objectForKey:@"building-mgmt.add-new-room.age"],
            [dictLanguage objectForKey:@"building-mgmt.add-new-room.cost-incurred-previous-year"],
            [dictLanguage objectForKey:@"building-mgmt.add-new-room.cost-incurred-current-year"],
            [dictLanguage objectForKey:@"building-mgmt.add-new-room.date-of-demolition"],
            [dictLanguage objectForKey:@"building-mgmt.add-new-room.demolition-reason"],
            [dictLanguage objectForKey:@"building-mgmt.add-new-room.contractor"],
        };
        
        NSString *objectType[] = {
            [NSString stringWithFormat:@"%d",b_room_name],
            [NSString stringWithFormat:@"%d",filter_service],
            [NSString stringWithFormat:@"%d",filter_camp],
            [NSString stringWithFormat:@"%d",filter_unit],
            [NSString stringWithFormat:@"%d",filter_building],
            [NSString stringWithFormat:@"%d",filter_floor],
            [NSString stringWithFormat:@"%d",filter_office],
            [NSString stringWithFormat:@"%d",filter_normal_ops],
            [NSString stringWithFormat:@"%d",b_square_metres],
            [NSString stringWithFormat:@"%d",b_date_of_completion],
            [NSString stringWithFormat:@"%d",b_warranty_date_exp],
            [NSString stringWithFormat:@"%d",b_construction_cost],
            [NSString stringWithFormat:@"%d",b_age],
            [NSString stringWithFormat:@"%d",b_cost_incurred_previous_year],
            [NSString stringWithFormat:@"%d",b_cost_incurred_current_year],
            [NSString stringWithFormat:@"%d",b_date_of_demolition],
            [NSString stringWithFormat:@"%d",b_demolition_reason],
            [NSString stringWithFormat:@"%d",filter_contractor],
        };
        
        NSMutableArray *objectValue = [NSMutableArray arrayWithCapacity:1];
        if (isEdit) {
            _lbMainTitle.text = [dictLanguage objectForKey:@"building-mgmt.edit-room.main-title"];
            
            //calculation new age for room if greater > 1 yrs since date of completion
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"MMM dd, yyyy"];
            NSDate *dateOfCompletion = [dateFormatter dateFromString:[itemDetailedDict objectForKey:@"date_of_completion"]];
            
            if (dateOfCompletion == nil)
                dateOfCompletion = [NSDate date];
            
            NSDate* now = [NSDate date];
            NSDateComponents* ageComponents = [[NSCalendar currentCalendar]
                                               components:NSYearCalendarUnit
                                               fromDate:dateOfCompletion
                                               toDate:now
                                               options:0];
            NSInteger age = [ageComponents year];
            
            NSString *newAge = [NSString stringWithFormat:@"%d",age];
            if ([newAge intValue] < 0)
                newAge = @"0";
            
            previousAge = [newAge intValue];
            
            //assign value to objectValue
            NSString *itemName = [itemDetailedDict objectForKey:@"item_name"] == nil ? [itemDetailedDict objectForKey:@"roomName"] : [itemDetailedDict objectForKey:@"item_name"];
            [objectValue addObject:itemName];
            [objectValue addObject:[itemDetailedDict objectForKey:@"service"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"camp"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"unit"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"building"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"floor"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"type"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"normal_ops"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"square_metres"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"date_of_completion"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"date_of_exp"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"construction_cost"]];
            [objectValue addObject:newAge];
            [objectValue addObject:[itemDetailedDict objectForKey:@"cost_incurred_previous_year"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"cost_incurred_current_year"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"date_of_demolition"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"demolition_reason"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"contractor"]];
            contratorId = [itemDetailedDict objectForKey:@"contractorId"] == nil ? @"0" : [itemDetailedDict objectForKey:@"contractorId"];
            
            [filterDictValue setObject:[itemDetailedDict objectForKey:@"service"] forKey:@"service"];
            [filterDictValue setObject:[itemDetailedDict objectForKey:@"camp"] forKey:@"camp"];
            [filterDictValue setObject:[itemDetailedDict objectForKey:@"unit"] forKey:@"unit"];
            [filterDictValue setObject:[itemDetailedDict objectForKey:@"building"] forKey:@"building"];
            
            
            //get service by name
            NSMutableDictionary *serviceDict = [CouchBaseLiteLib getServiceByName:[itemDetailedDict objectForKey:@"service"]];
            serviceId = [serviceDict objectForKey:@"_id"];
            
            NSMutableDictionary *campDict = [CouchBaseLiteLib getCampByService:serviceId andCampName:[itemDetailedDict objectForKey:@"camp"]];
            campId = [campDict objectForKey:@"idCamp"];
            
            NSMutableDictionary *unitDict = [CouchBaseLiteLib getUnitByService:serviceId andCamp:campId andUnitName:[itemDetailedDict objectForKey:@"unit"]];
            unitId = [unitDict objectForKey:@"idUnit"];
            
            NSMutableDictionary *buildingDict = [CouchBaseLiteLib getBuildingByName:[itemDetailedDict objectForKey:@"building"]];
            buildingId = [buildingDict objectForKey:@"_id"];
        }
        else {
            //set default value
            NSString *tmpObjectValue[] = {
                @"",
                [dictLanguage objectForKey:@"filter.select-service"],
                [dictLanguage objectForKey:@"filter.select-camp"],
                [dictLanguage objectForKey:@"filter.select-unit"],
                [dictLanguage objectForKey:@"filter.select-building"],
                [dictLanguage objectForKey:@"filter.select-floor"],
                [dictLanguage objectForKey:@"schedule.title-select"],
                [dictLanguage objectForKey:@"building-mgmt.add-new-room.type-normal"],
                @"",
                @"",
                @"",
                @"0",
                @"0",
                @"0",
                @"0",
                @"",
                @"NA",
                [dictLanguage objectForKey:@"schedule.title-select"]
            };
            for (int i=0;i < sizeof(tmpObjectValue)/sizeof(tmpObjectValue[i]);i++) {
                [objectValue addObject:tmpObjectValue[i]];
            }
        }
        
        //initialize dictionary to store these value
        for (int i=0;i < sizeof(lbTitle)/sizeof(lbTitle[0]);i++) {
            NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:lbTitle[i],@"labelTitle",objectType[i],@"objectType",[objectValue objectAtIndex:i],@"objectValue", nil];
            [mainArray addObject:dict];
        }
    }
    else {
        _lbMainTitle.text = [dictLanguage objectForKey:@"facility.add-new-equipment.main-title"];
        
        //there are 27 rows
        NSString *lbTitle[] = {
            [dictLanguage objectForKey:@"facility.add-new-equipment.equipment-id"],
            [dictLanguage objectForKey:@"schedule.title-service"],
            [dictLanguage objectForKey:@"schedule.title-camp"],
            [dictLanguage objectForKey:@"schedule.title-unit"],
            [dictLanguage objectForKey:@"schedule.title-building"],
            [dictLanguage objectForKey:@"schedule.title-floor"],
            [dictLanguage objectForKey:@"schedule.title-room"],
            [dictLanguage objectForKey:@"facility.add-new-equipment.system"],
            [dictLanguage objectForKey:@"facility.add-new-equipment.description"],
            [dictLanguage objectForKey:@"facility.add-new-equipment.brand"],
            [dictLanguage objectForKey:@"facility.add-new-equipment.serial"],
            [dictLanguage objectForKey:@"facility.add-new-equipment.make-model"],
            [dictLanguage objectForKey:@"facility.add-new-equipment.capacity"],
            [dictLanguage objectForKey:@"facility.add-new-equipment.expiry-date"],
            [dictLanguage objectForKey:@"facility.add-new-equipment.manufacture-detail"],
            [dictLanguage objectForKey:@"facility.add-new-equipment.agent-detail"],
            [dictLanguage objectForKey:@"facility.add-new-equipment.normal-critical"],
            [dictLanguage objectForKey:@"facility.add-new-equipment.capital-cost"],
            [dictLanguage objectForKey:@"facility.add-new-equipment.date-of-installation"],
            [dictLanguage objectForKey:@"facility.add-new-equipment.age"],
            [dictLanguage objectForKey:@"facility.add-new-equipment.amp-frequency"],
            [dictLanguage objectForKey:@"facility.add-new-equipment.amp-budciet"],
            [dictLanguage objectForKey:@"facility.add-new-equipment.cost-incurred-previous-year"],
            [dictLanguage objectForKey:@"facility.add-new-equipment.cost-incurred-current-year"],
            [dictLanguage objectForKey:@"facility.add-new-equipment.date-of-condemnation"],
            [dictLanguage objectForKey:@"facility.add-new-equipment.condemnation-reason"],
            [dictLanguage objectForKey:@"facility.add-new-equipment.contractor"],
        };
        
        NSString *objectType[] = {
            [NSString stringWithFormat:@"%d",f_equipment_id],
            [NSString stringWithFormat:@"%d",filter_service],
            [NSString stringWithFormat:@"%d",filter_camp],
            [NSString stringWithFormat:@"%d",filter_unit],
            [NSString stringWithFormat:@"%d",filter_building],
            [NSString stringWithFormat:@"%d",filter_floor],
            [NSString stringWithFormat:@"%d",filter_room],
            [NSString stringWithFormat:@"%d",filter_system],
            [NSString stringWithFormat:@"%d",filter_description],
            [NSString stringWithFormat:@"%d",f_brand],
            [NSString stringWithFormat:@"%d",f_serial_no],
            [NSString stringWithFormat:@"%d",f_make_model],
            [NSString stringWithFormat:@"%d",f_capacity],
            [NSString stringWithFormat:@"%d",f_expiry_date],
            [NSString stringWithFormat:@"%d",f_manufacture_detail],
            [NSString stringWithFormat:@"%d",f_agent_detail],
            [NSString stringWithFormat:@"%d",filter_normal_ops],
            [NSString stringWithFormat:@"%d",f_capital_cost],
            [NSString stringWithFormat:@"%d",f_date_of_installation],
            [NSString stringWithFormat:@"%d",f_age],
            [NSString stringWithFormat:@"%d",f_amp_frequency],
            [NSString stringWithFormat:@"%d",f_amp_budciet],
            [NSString stringWithFormat:@"%d",f_cost_incurred_previous_year],
            [NSString stringWithFormat:@"%d",f_cost_incurred_current_year],
            [NSString stringWithFormat:@"%d",f_date_of_condemnation],
            [NSString stringWithFormat:@"%d",f_condemnation_reason],
            [NSString stringWithFormat:@"%d",filter_contractor],
        };
        
        BOOL isOther = [[itemDetailedDict objectForKey:@"isOther"] boolValue];
        
        NSMutableArray *objectValue = [NSMutableArray arrayWithCapacity:1];
        if (isEdit) {
            _lbMainTitle.text = [dictLanguage objectForKey:@"facility.edit-equipment.main-title"];
            
            //calculation new age for room if greater > 1 yrs since date of completion
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"MMM dd, yyyy"];
            NSDate *dateOfInstallation = [dateFormatter dateFromString:[itemDetailedDict objectForKey:@"date_of_installation"]];
            
            if (dateOfInstallation == nil)
                dateOfInstallation = [NSDate date];
            
            NSDate* now = [NSDate date];
            NSDateComponents* ageComponents = [[NSCalendar currentCalendar]
                                               components:NSYearCalendarUnit
                                               fromDate:dateOfInstallation
                                               toDate:now
                                               options:0];
            NSInteger age = [ageComponents year];
            
            NSString *newAge = [NSString stringWithFormat:@"%d",age];
            if ([newAge intValue] < 0)
                newAge = @"0";
            
            previousAge = [newAge intValue];
            
            //assign value to objectValue
            NSString *itemName = [itemDetailedDict objectForKey:@"item_name"] == nil ? [itemDetailedDict objectForKey:@"name"] : [itemDetailedDict objectForKey:@"item_name"];
            [objectValue addObject:itemName];
            [objectValue addObject:[itemDetailedDict objectForKey:@"service"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"camp"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"unit"]];
            
            if (isOther)
                [objectValue addObject:[dictLanguage objectForKey:@"filter.select-building.other"]];
            else
                [objectValue addObject:[itemDetailedDict objectForKey:@"building"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"floor"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"room"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"system"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"description"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"brand"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"serial_no"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"make_model"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"capacity"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"date_of_exp"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"manufacturer_detail"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"agent_detail"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"normal_ops"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"capital_cost"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"date_of_installation"] == nil ? @"" : [itemDetailedDict objectForKey:@"date_of_installation"]];
            [objectValue addObject:newAge];
            [objectValue addObject:[itemDetailedDict objectForKey:@"amp_frequency"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"amp_budciet"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"cost_incurred_previous_year"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"cost_incurred_current_year"]];
            
            [objectValue addObject:[itemDetailedDict objectForKey:@"date_of_condemnation"] == nil ? @"" : [itemDetailedDict objectForKey:@"date_of_condemnation"]];
        
            [objectValue addObject:[itemDetailedDict objectForKey:@"condemnation_reason"]];
            [objectValue addObject:[itemDetailedDict objectForKey:@"contractor"]];
            contratorId = [itemDetailedDict objectForKey:@"contractorId"] == nil ? @"0" : [itemDetailedDict objectForKey:@"contractorId"];
            
            [filterDictValue setObject:[itemDetailedDict objectForKey:@"service"] forKey:@"service"];
            [filterDictValue setObject:[itemDetailedDict objectForKey:@"camp"] forKey:@"camp"];
            [filterDictValue setObject:[itemDetailedDict objectForKey:@"unit"] forKey:@"unit"];
            [filterDictValue setObject:[itemDetailedDict objectForKey:@"building"] forKey:@"building"];
            [filterDictValue setObject:[itemDetailedDict objectForKey:@"floor"] forKey:@"floor"];
            [filterDictValue setObject:[itemDetailedDict objectForKey:@"room"] forKey:@"room"];
            [filterDictValue setObject:[itemDetailedDict objectForKey:@"system"] forKey:@"system"];
            [filterDictValue setObject:[itemDetailedDict objectForKey:@"description"] forKey:@"description"];
            
            //get service by name
            NSMutableDictionary *serviceDict = [CouchBaseLiteLib getServiceByName:[itemDetailedDict objectForKey:@"service"]];
            serviceId = [serviceDict objectForKey:@"_id"];
            
            NSMutableDictionary *campDict = [CouchBaseLiteLib getCampByService:serviceId andCampName:[itemDetailedDict objectForKey:@"camp"]];
            campId = [campDict objectForKey:@"idCamp"];
            
            NSMutableDictionary *unitDict = [CouchBaseLiteLib getUnitByService:serviceId andCamp:campId andUnitName:[itemDetailedDict objectForKey:@"unit"]];
            unitId = [unitDict objectForKey:@"idUnit"];
            
            NSMutableDictionary *buildingDict = [CouchBaseLiteLib getBuildingByName:[itemDetailedDict objectForKey:@"building"]];
            buildingId = [buildingDict objectForKey:@"_id"];
            
            NSMutableDictionary *floorDict = [CouchBaseLiteLib getFloorByBuilding:[itemDetailedDict objectForKey:@"building"] andFloorName:[itemDetailedDict objectForKey:@"floor"]];
            floorId = [floorDict objectForKey:@"id"] == nil ? @"0" : [floorDict objectForKey:@"id"];
            
            systemName = [itemDetailedDict objectForKey:@"system"];
        }
        else {
            //set default value
            NSString *tmpObjectValue[] = {
                @"",
                [dictLanguage objectForKey:@"filter.select-service"],
                [dictLanguage objectForKey:@"filter.select-camp"],
                [dictLanguage objectForKey:@"filter.select-unit"],
                [dictLanguage objectForKey:@"filter.select-building"],
                [dictLanguage objectForKey:@"filter.select-floor"],
                [dictLanguage objectForKey:@"filter.select-room"],
                [dictLanguage objectForKey:@"filter.select-system"],
                [dictLanguage objectForKey:@"filter.select-description"],
                @"",
                @"",
                @"",
                @"",
                @"",
                @"",
                @"NA",
                [dictLanguage objectForKey:@"building-mgmt.add-new-room.type-normal"],
                @"0",
                @"",
                @"0",
                @"",
                @"",
                @"0",
                @"0",
                @"",
                @"NA",
                [dictLanguage objectForKey:@"schedule.title-select"]
            };
            
            for (int i=0;i < sizeof(tmpObjectValue)/sizeof(tmpObjectValue[0]);i++) {
                [objectValue addObject:tmpObjectValue[i]];
            }
        }
        
        //initialize dictionary to store these value
        for (int i=0;i < sizeof(lbTitle)/sizeof(lbTitle[0]);i++) {
            NSMutableDictionary *dict;
            dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:lbTitle[i],@"labelTitle",objectType[i],@"objectType",[objectValue objectAtIndex:i],@"objectValue", nil];
            [mainArray addObject:dict];
        }
        
        if (isEdit && isOther) {
            //reload data when building = other

            //remove floor and room row: index = 5 & 6
            NSMutableArray *tmpIndexPaths = [NSMutableArray arrayWithCapacity:1];
            NSIndexPath *path1 = [NSIndexPath indexPathForRow:5 inSection:0];
            NSIndexPath *path2 = [NSIndexPath indexPathForRow:6 inSection:0];
            [tmpIndexPaths addObject:path1];
            
            //if select Room, only remove floor row
            if (itemType != Building_Type)
                [tmpIndexPaths addObject:path2];
            
            //delete floor,room
            if ([tmpIndexPaths count] > 0) {
                NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
                [indexSet addIndex:5];
                
                //if select Room, only remove floor row
                if (itemType != Building_Type)
                    [indexSet addIndex:6];
                
                [mainArray removeObjectsAtIndexes:indexSet];
                [self.mainTableView deleteRowsAtIndexPaths:tmpIndexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
                
                //add other building row
                [tmpIndexPaths removeAllObjects];
                NSIndexPath *path3 = [NSIndexPath indexPathForRow:5 inSection:0];
                [tmpIndexPaths addObject:path3];
                
                NSMutableDictionary *locationDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"",@"labelTitle",[NSNumber numberWithInt:filter_location],@"objectType",[itemDetailedDict objectForKey:@"building"],@"objectValue", nil];
                [mainArray insertObject:locationDict atIndex:5];
                
                [self.mainTableView insertRowsAtIndexPaths:tmpIndexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
            }
            
        }
    }
    
    //set contensize for mainscrollview
    _mainScrollView.contentSize = CGSizeMake(_mainScrollView.frame.size.width, [mainArray count]*_mainTableView.rowHeight);
    _mainTableView.frame = CGRectMake(_mainTableView.frame.origin.x, _mainTableView.frame.origin.y, _mainTableView.frame.size.width, [mainArray count]*_mainTableView.rowHeight);
    
    //listen keyboard appear
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow) name:UIKeyboardDidShowNotification object:nil];
    
    //listen keyboard disappear
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide) name:UIKeyboardDidHideNotification object:nil];
}

- (void) keyboardDidShow {
//    _mainTableView.frame = CGRectMake(_mainTableView.frame.origin.x, _mainTableView.frame.origin.y, _mainTableView.frame.size.width, 327);
    _mainScrollView.frame = CGRectMake(_mainScrollView.frame.origin.x, _mainScrollView.frame.origin.y, _mainScrollView.frame.size.width, 457);
    _mainTableView.frame = CGRectMake(_mainTableView.frame.origin.x, _mainTableView.frame.origin.y, _mainTableView.frame.size.width, [mainArray count]*_mainTableView.rowHeight);
    [_mainScrollView setContentSize:CGSizeMake(_mainTableView.frame.size.width, _mainTableView.frame.size.height+100)];
}

- (void) keyboardDidHide {
//    _mainTableView.frame = CGRectMake(_mainTableView.frame.origin.x, _mainTableView.frame.origin.y, _mainTableView.frame.size.width, 627);
    _mainScrollView.frame = CGRectMake(_mainScrollView.frame.origin.x, _mainScrollView.frame.origin.y, _mainScrollView.frame.size.width, 627);
    _mainScrollView.contentSize = CGSizeMake(_mainScrollView.frame.size.width, [mainArray count]*_mainTableView.rowHeight);
}

- (void) selectComboBox:(UIButton*)sender {
    int filterType = sender.tag;
    
    //init controller to filter value
    FilterViewController *controller = [[FilterViewController alloc] initWithStyle:UITableViewStylePlain filterType:filterType];
    controller.delegate = self;
    controller.filterValueDict = filterDictValue;
    controller.itemType = itemType;
    
    switch (filterType) {
        case filter_floor:
            controller.buildingId = buildingId;
            break;
        case filter_service:
            controller.serviceId = serviceId;
            break;
        case filter_camp:
            controller.serviceId = serviceId;
            controller.campId = campId;
            break;
        case filter_unit:
            controller.serviceId = serviceId;
            controller.campId = campId;
            break;
        case filter_building:
        case filter_location:
            controller.unitId = unitId;
            break;
        case filter_description:
            controller.systemName = systemName;
            break;
        default:
            break;
    }
    
    popoverController = [[UIPopoverController alloc] initWithContentViewController:controller];
    [popoverController presentPopoverFromRect:sender.frame inView:[sender superview] permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

- (void) selectDate:(UIButton*)sender {
    //dismiss popover before presenting another one
    [popoverController dismissPopoverAnimated:YES];
    
    DatePickerViewController *controller = [[DatePickerViewController alloc] initWithNibName:@"DatePickerViewController" bundle:[NSBundle mainBundle] dateSelect:[NSDate date] paramSender:sender];
    controller.delegate = self;
    
    popoverController = [[UIPopoverController alloc] initWithContentViewController:controller];
    [popoverController presentPopoverFromRect:sender.frame inView:[sender superview] permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    controller.datePicker.datePickerMode = UIDatePickerModeDate;
}

#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 2) {
        //set date of completion / date of installation bases on input Age
        int objectTag;
        if (itemType == Building_Type) {
            objectTag = b_date_of_completion;
        }
        else {
            objectTag = f_date_of_installation;
        }
        
        //calculate the date from Age
        NSDate *now = [NSDate date];
        
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:now];
        
        int day     = [components day];
        int month   = [components month];
        int year    = [components year];
        //increase year
        year -= currentAge;
        
        [components setDay:day];
        [components setMonth:month];
        [components setYear:year];
        NSDate *newDate = [calendar dateFromComponents:components];
        
        //convert to MMM dd, yyyy
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"MMM dd, yyyy"];

        NSString *newDateStr = [dateFormatter stringFromDate:newDate];
        
        for (int i=0;i < [mainArray count];i++) {
            NSMutableDictionary *tmpDict = [mainArray objectAtIndex:i];
            int objectType = [[tmpDict objectForKey:@"objectType"] intValue];
            if (objectType == objectTag) {
                [tmpDict setObject:newDateStr forKey:@"objectValue"];
            }
        }
        NSLog(@"mainArray = %@",mainArray);
        [self saveItem:nil];
    }
    else {
        [self.navigationController popViewControllerAnimated:YES];
        if ([parent isKindOfClass:[DetailedItemViewController class]]) {
            //check age again
            //calculation new age for room if greater > 1 yrs since date of completion
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"MMM dd, yyyy"];
            
            NSDate *dateOfCompletion;
            if ([[itemDetailedDict objectForKey:@"Table"] isEqualToString:BuildingMgmtDoc])
                dateOfCompletion = [dateFormatter dateFromString:[itemDetailedDict objectForKey:@"date_of_completion"]];
            else
                dateOfCompletion = [dateFormatter dateFromString:[itemDetailedDict objectForKey:@"date_of_installation"]];
            if (dateOfCompletion == nil)
                dateOfCompletion = [NSDate date];
            
            NSDate* now = [NSDate date];
            NSDateComponents* ageComponents = [[NSCalendar currentCalendar]
                                               components:NSYearCalendarUnit
                                               fromDate:dateOfCompletion
                                               toDate:now
                                               options:0];
            NSInteger age = [ageComponents year];
            
            NSString *newAge = [NSString stringWithFormat:@"%d",age];
            if ([newAge intValue] < 0)
                newAge = @"0";
            NSMutableDictionary *tmpDict = [itemDetailedDict mutableCopy];
            [tmpDict setObject:newAge forKey:@"age"];
            
            [((DetailedItemViewController*)parent).detailedInfoController reloadAfterUpdate:tmpDict];
        }
        else if ([parent isKindOfClass:[BuildingMgmtViewController class]]) {
            if (itemType == Building_Type)
                [(BuildingMgmtViewController*)parent listRoom];
            else
                [(BuildingMgmtViewController*)parent listEquipment];
            [((BuildingMgmtViewController*)parent).mainTableView reloadData];
        }
    }
}

#pragma mark FilterViewDelegate

- (void) didSelectFilter:(NSMutableDictionary *)filterDict {
    [popoverController dismissPopoverAnimated:YES];
    int filterType = [[filterDict objectForKey:@"filterType"] intValue];
    
    BOOL isSelectRoom = NO;
    //get all object in tableview and set value
    for (int i=0;i < [mainArray count];i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
        UITableViewCell *cell = [_mainTableView cellForRowAtIndexPath:indexPath];
        
        for (UIButton *subview in cell.contentView.subviews) {
            if ([subview isKindOfClass:[UIButton class]]) {
                if (subview.tag == filterType){
                    //get dictionary of this row
                    NSMutableDictionary *dict = [mainArray objectAtIndex:i];
                    
                    switch (subview.tag) {
                        case filter_service:
                            serviceId = [filterDict objectForKey:@"index"];
                            [dict setObject:serviceId forKey:@"serviceId"];
                            //if select service, reset camp and unit
                            campId = @"0";
                            unitId = @"0";
                            buildingId = @"0";
                            floorId = @"0";
                            systemId = @"0";
                            descriptionId = @"0";
                            roomId = @"0";
                            
                            //set filter dict
                            [filterDictValue setObject:[filterDict objectForKey:@"filterName"] forKey:@"service"];
                            if ([serviceId isEqualToString:@"0"])
                                [filterDictValue setObject:@"0" forKey:@"service"];
                            [filterDictValue setObject:@"0" forKey:@"camp"];
                            [filterDictValue setObject:@"0" forKey:@"unit"];
                            [filterDictValue setObject:@"0" forKey:@"building"];
                            [filterDictValue setObject:@"0" forKey:@"floor"];
                            [filterDictValue setObject:@"0" forKey:@"room"];
                            
                            //appear floor, room,
                            //check if total row hasn't changed, dont insert row
                            int countRow = itemType == Building_Type ? 19 : 27;
                            if ([mainArray count] < countRow) {
                                NSMutableArray *tmpIndexPaths = [NSMutableArray arrayWithCapacity:1];
                                
                                //remove filter location
                                NSIndexPath *path = [NSIndexPath indexPathForRow:5 inSection:0];
                                [tmpIndexPaths addObject:path];
                                NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
                                [indexSet addIndex:5];
                                [mainArray removeObjectsAtIndexes:indexSet];
                                
                                [self.mainTableView deleteRowsAtIndexPaths:tmpIndexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
                                
                                //insert two row floor, room
                                [tmpIndexPaths removeAllObjects];
                                
                                NSMutableDictionary *floorDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[dictLanguage objectForKey:@"schedule.title-floor"],@"labelTitle",[NSNumber numberWithInt:filter_floor],@"objectType",[dictLanguage objectForKey:@"filter.select-floor"],@"objectValue", nil];
                                [mainArray insertObject:floorDict atIndex:5];
                                NSIndexPath *path1 = [NSIndexPath indexPathForRow:5 inSection:0];
                                [tmpIndexPaths addObject:path1];
                                
                                //if select Room, only remove floor row
                                if (itemType != Building_Type) {
                                    NSMutableDictionary *roomDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[dictLanguage objectForKey:@"schedule.title-room"],@"labelTitle",[NSNumber numberWithInt:filter_room],@"objectType",[dictLanguage objectForKey:@"filter.select-room"],@"objectValue", nil];
                                    [mainArray insertObject:roomDict atIndex:6];
                                    NSIndexPath *path2 = [NSIndexPath indexPathForRow:6 inSection:0];
                                    [tmpIndexPaths addObject:path2];
                                }
                                
                                [self.mainTableView insertRowsAtIndexPaths:tmpIndexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
                            }
                            
                            break;
                        case filter_camp:
                        {
                            campId = [filterDict objectForKey:@"index"];
                            [dict setObject:campId forKey:@"campId"];
                            
                            unitId = @"0";
                            buildingId = @"0";
                            floorId = @"0";
                            systemId = @"0";
                            descriptionId = @"0";
                            roomId = @"0";
                            
                            [filterDictValue setObject:[filterDict objectForKey:@"filterName"] forKey:@"camp"];
                            if ([campId isEqualToString:@"0"])
                                [filterDictValue setObject:@"0" forKey:@"camp"];

                            [filterDictValue setObject:@"0" forKey:@"unit"];
                            [filterDictValue setObject:@"0" forKey:@"building"];
                            [filterDictValue setObject:@"0" forKey:@"floor"];
                            [filterDictValue setObject:@"0" forKey:@"room"];
                            
                            //appear floor, room,
                            //check if total row hasn't changed, dont insert row
                            int countRow = itemType == Building_Type ? 19 : 27;
                            if ([mainArray count] < countRow) {
                                NSMutableArray *tmpIndexPaths = [NSMutableArray arrayWithCapacity:1];
                                
                                //remove filter location
                                NSIndexPath *path = [NSIndexPath indexPathForRow:5 inSection:0];
                                [tmpIndexPaths addObject:path];
                                NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
                                [indexSet addIndex:5];
                                [mainArray removeObjectsAtIndexes:indexSet];
                                
                                [self.mainTableView deleteRowsAtIndexPaths:tmpIndexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
                                
                                //insert two row floor, room
                                [tmpIndexPaths removeAllObjects];
                                
                                NSMutableDictionary *floorDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[dictLanguage objectForKey:@"schedule.title-floor"],@"labelTitle",[NSNumber numberWithInt:filter_floor],@"objectType",[dictLanguage objectForKey:@"filter.select-floor"],@"objectValue", nil];
                                [mainArray insertObject:floorDict atIndex:5];
                                NSIndexPath *path1 = [NSIndexPath indexPathForRow:5 inSection:0];
                                [tmpIndexPaths addObject:path1];
                                
                                //if select Room, only remove floor row
                                if (itemType != Building_Type) {
                                    NSMutableDictionary *roomDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[dictLanguage objectForKey:@"schedule.title-room"],@"labelTitle",[NSNumber numberWithInt:filter_room],@"objectType",[dictLanguage objectForKey:@"filter.select-room"],@"objectValue", nil];
                                    [mainArray insertObject:roomDict atIndex:6];
                                    NSIndexPath *path2 = [NSIndexPath indexPathForRow:6 inSection:0];
                                    [tmpIndexPaths addObject:path2];
                                }
                                
                                [self.mainTableView insertRowsAtIndexPaths:tmpIndexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
                            }

                            break;
                        }
                        case filter_building:
                            buildingId = [filterDict objectForKey:@"index"];
                            [dict setObject:buildingId forKey:@"buildingId"];
                            
                            floorId = @"0";
                            roomId  = @"0";
                            
                            [filterDictValue setObject:[filterDict objectForKey:@"filterName"] forKey:@"building"];
                            if ([buildingId isEqualToString:@"0"])
                                [filterDictValue setObject:@"0" forKey:@"building"];

                            [filterDictValue setObject:@"0" forKey:@"floor"];
                            [filterDictValue setObject:@"0" forKey:@"room"];
                            
                            //set the first document for other building
                            if ([[filterDict objectForKey:@"filterName"] isEqualToString:[dictLanguage objectForKey:@"filter.select-building.other"]]) {
                                if ([mainArray count] < 27) ;
                                else {
                                    //get list location and set the first row for btnSelectLocation
                                    NSMutableArray *otherBuildingArray = [CouchBaseLiteLib listOtherBuildingByUnit:unitId from:0 numberRow:NUMBER_ROW_PAGE];
                                    if ([otherBuildingArray count] > 0) {
                                        NSMutableDictionary *otherBuildingDict = [otherBuildingArray objectAtIndex:0];
                                        
                                        buildingId = [filterDict objectForKey:@"index"];
                                        
                                        //remove floor and room row: index = 5 & 6
                                        NSMutableArray *tmpIndexPaths = [NSMutableArray arrayWithCapacity:1];
                                        NSIndexPath *path1 = [NSIndexPath indexPathForRow:5 inSection:0];
                                        NSIndexPath *path2 = [NSIndexPath indexPathForRow:6 inSection:0];
                                        [tmpIndexPaths addObject:path1];
                                        
                                        //if select Room, only remove floor row
                                        if (itemType != Building_Type)
                                            [tmpIndexPaths addObject:path2];
                                        
                                        //delete floor,room
                                        if ([tmpIndexPaths count] > 0) {
                                            NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
                                            [indexSet addIndex:5];
                                            
                                            //if select Room, only remove floor row
                                            if (itemType != Building_Type)
                                                [indexSet addIndex:6];
                                            
                                            [mainArray removeObjectsAtIndexes:indexSet];
                                            [self.mainTableView deleteRowsAtIndexPaths:tmpIndexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
                                            
                                            //add other building row
                                            [tmpIndexPaths removeAllObjects];
                                            NSIndexPath *path3 = [NSIndexPath indexPathForRow:5 inSection:0];
                                            [tmpIndexPaths addObject:path3];
                                            
                                            NSMutableDictionary *locationDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"",@"labelTitle",[NSNumber numberWithInt:filter_location],@"objectType",[otherBuildingDict objectForKey:@"filterName"],@"objectValue", nil];
                                            [mainArray insertObject:locationDict atIndex:5];
                                            
                                            [filterDictValue setObject:[otherBuildingDict objectForKey:@"filterName"] forKey:@"building"];
                                            
                                            [self.mainTableView insertRowsAtIndexPaths:tmpIndexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
                                        }
                                    }
                                }
                            }
                            else {
                                //appear floor, room,
                                //check if total row hasn't changed, dont insert row
                                int countRow = itemType == Building_Type ? 19 : 27;
                                if ([mainArray count] < countRow) {
                                    NSMutableArray *tmpIndexPaths = [NSMutableArray arrayWithCapacity:1];
                                    
                                    //remove filter location
                                    NSIndexPath *path = [NSIndexPath indexPathForRow:5 inSection:0];
                                    [tmpIndexPaths addObject:path];
                                    NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
                                    [indexSet addIndex:5];
                                    [mainArray removeObjectsAtIndexes:indexSet];
                                    
                                    [self.mainTableView deleteRowsAtIndexPaths:tmpIndexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
                                    
                                    //insert two row floor, room
                                    [tmpIndexPaths removeAllObjects];
                                    
                                    NSMutableDictionary *floorDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[dictLanguage objectForKey:@"schedule.title-floor"],@"labelTitle",[NSNumber numberWithInt:filter_floor],@"objectType",[dictLanguage objectForKey:@"filter.select-floor"],@"objectValue", nil];
                                    [mainArray insertObject:floorDict atIndex:5];
                                    NSIndexPath *path1 = [NSIndexPath indexPathForRow:5 inSection:0];
                                    [tmpIndexPaths addObject:path1];
                                    
                                    //if select Room, only remove floor row
                                    if (itemType != Building_Type) {
                                        NSMutableDictionary *roomDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[dictLanguage objectForKey:@"schedule.title-room"],@"labelTitle",[NSNumber numberWithInt:filter_room],@"objectType",[dictLanguage objectForKey:@"filter.select-room"],@"objectValue", nil];
                                        [mainArray insertObject:roomDict atIndex:6];
                                        NSIndexPath *path2 = [NSIndexPath indexPathForRow:6 inSection:0];
                                        [tmpIndexPaths addObject:path2];
                                    }
                                    
                                    [self.mainTableView insertRowsAtIndexPaths:tmpIndexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
                                }
                            }

                            break;
                            
                        case filter_location:
                            buildingId = [filterDict objectForKey:@"index"];
                            [dict setObject:buildingId forKey:@"buildingId"];
                            
                            floorId = @"0";
                            roomId  = @"0";
                            
                            [filterDictValue setObject:[filterDict objectForKey:@"filterName"] forKey:@"building"];
                            if ([buildingId isEqualToString:@"0"])
                                [filterDictValue setObject:@"0" forKey:@"building"];
                            
                            [filterDictValue setObject:@"0" forKey:@"floor"];
                            [filterDictValue setObject:@"0" forKey:@"room"];
                            break;
                        case filter_unit:
                        {
                            unitId = [filterDict objectForKey:@"index"];
                            [dict setObject:unitId forKey:@"unitId"];
                            
                            roomId = @"0";
                            
                            [filterDictValue setObject:[filterDict objectForKey:@"filterName"] forKey:@"unit"];
                            if ([unitId isEqualToString:@"0"])
                                [filterDictValue setObject:@"0" forKey:@"unit"];
                            [filterDictValue setObject:@"0" forKey:@"room"];
                            
                            //appear floor, room,
                            //check if total row hasn't changed, dont insert row
                            int countRow = itemType == Building_Type ? 19 : 27;
                            if ([mainArray count] < countRow) {
                                NSMutableArray *tmpIndexPaths = [NSMutableArray arrayWithCapacity:1];
                                
                                //remove filter location
                                NSIndexPath *path = [NSIndexPath indexPathForRow:5 inSection:0];
                                [tmpIndexPaths addObject:path];
                                NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
                                [indexSet addIndex:5];
                                [mainArray removeObjectsAtIndexes:indexSet];
                                
                                [self.mainTableView deleteRowsAtIndexPaths:tmpIndexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
                                
                                //insert two row floor, room
                                [tmpIndexPaths removeAllObjects];
                                
                                NSMutableDictionary *floorDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[dictLanguage objectForKey:@"schedule.title-floor"],@"labelTitle",[NSNumber numberWithInt:filter_floor],@"objectType",[dictLanguage objectForKey:@"filter.select-floor"],@"objectValue", nil];
                                [mainArray insertObject:floorDict atIndex:5];
                                NSIndexPath *path1 = [NSIndexPath indexPathForRow:5 inSection:0];
                                [tmpIndexPaths addObject:path1];
                                
                                //if select Room, only remove floor row
                                if (itemType != Building_Type) {
                                    NSMutableDictionary *roomDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[dictLanguage objectForKey:@"schedule.title-room"],@"labelTitle",[NSNumber numberWithInt:filter_room],@"objectType",[dictLanguage objectForKey:@"filter.select-room"],@"objectValue", nil];
                                    [mainArray insertObject:roomDict atIndex:6];
                                    NSIndexPath *path2 = [NSIndexPath indexPathForRow:6 inSection:0];
                                    [tmpIndexPaths addObject:path2];
                                }
                                
                                [self.mainTableView insertRowsAtIndexPaths:tmpIndexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
                            }

                            break;
                        }
                        case filter_floor:
                            floorId = [filterDict objectForKey:@"index"];
                            [dict setObject:floorId forKey:@"floorId"];
                            
                            roomId = @"0";
                            
                            [filterDictValue setObject:[filterDict objectForKey:@"filterName"] forKey:@"floor"];
                            if ([floorId isEqualToString:@"0"])
                                [filterDictValue setObject:@"0" forKey:@"floor"];
                            [filterDictValue setObject:@"0" forKey:@"room"];
                            
                            break;
                        case filter_system:
                            systemId = [filterDict objectForKey:@"index"];
                            [dict setObject:systemId forKey:@"systemId"];
                            
                            systemName = [filterDict objectForKey:@"filterName"];
                            
                            //reset description
                            descriptionId = @"0";
                            break;
                        case filter_description:
                            descriptionId = [filterDict objectForKey:@"index"];
                            [dict setObject:descriptionId forKey:@"descriptionId"];
                            break;
                        case filter_contractor:
                        {
                            NSString *table = [filterDict objectForKey:@"Table"];
                            if ([table isEqualToString:kUserDocType])
                                contratorId = [filterDict objectForKey:@"index"];
                            else {
                                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                                contratorId = [userDefaults objectForKey:ACCOUNT_ID];
                            }
                            [dict setObject:contratorId forKey:@"contractorId"];
                            break;
                        }
                        case filter_room:
                            isSelectRoom = YES;
                            [filterDictValue setObject:[filterDict objectForKey:@"filterName"] forKey:@"room"];
                            break;
                        default:
                            break;
                    }
                    
                    [dict setObject:[filterDict objectForKey:@"filterName"] forKey:@"objectValue"];
                    [subview setTitle:[filterDict objectForKey:@"filterName"] forState:UIControlStateNormal];
                    break;
                }
            }
        }
    }
    
    //if select contractor then dont reset
    if (filterType != filter_contractor) {
        //if select room thi ko reset room
        if (!isSelectRoom) {
            if ([campId isEqualToString:@"0"]) {
                //get all object in tableview and set value
                for (int i=0;i < [mainArray count];i++) {
                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                    UITableViewCell *cell = [_mainTableView cellForRowAtIndexPath:indexPath];
                    
                    //loop to reset select camp and unit
                    for (UIButton *subview1 in cell.contentView.subviews) {
                        NSMutableDictionary *dict = [mainArray objectAtIndex:i];
                        
                        if ([subview1 isKindOfClass:[UIButton class]]) {
                            if (subview1.tag == filter_camp){
                                [dict setObject:[dictLanguage objectForKey:@"filter.select-camp"] forKey:@"objectValue"];
                                [subview1 setTitle:[dictLanguage objectForKey:@"filter.select-camp"] forState:UIControlStateNormal];
                            }
                            else if (subview1.tag == filter_unit) {
                                [dict setObject:[dictLanguage objectForKey:@"filter.select-unit"] forKey:@"objectValue"];
                                [subview1 setTitle:[dictLanguage objectForKey:@"filter.select-unit"] forState:UIControlStateNormal];
                            }
                            else if (subview1.tag == filter_building) {
                                if ([[dict objectForKey:@"objectValue"] isEqualToString:[dictLanguage objectForKey:@"filter.select-building.other"]]) {
                                    //do nothing
                                }
                                else {
                                    [dict setObject:[dictLanguage objectForKey:@"filter.select-building"] forKey:@"objectValue"];
                                    [subview1 setTitle:[dictLanguage objectForKey:@"filter.select-building"] forState:UIControlStateNormal];
                                }
                            }
                            else if (subview1.tag == filter_floor) {
                                [dict setObject:[dictLanguage objectForKey:@"filter.select-floor"] forKey:@"objectValue"];
                                [subview1 setTitle:[dictLanguage objectForKey:@"filter.select-floor"] forState:UIControlStateNormal];
                            }
                            else if (subview1.tag == filter_system) {
                                [dict setObject:[dictLanguage objectForKey:@"filter.select-system"] forKey:@"objectValue"];
                                [subview1 setTitle:[dictLanguage objectForKey:@"filter.select-system"] forState:UIControlStateNormal];
                            }
                            else if (subview1.tag == filter_description) {
                                [dict setObject:[dictLanguage objectForKey:@"filter.select-description"] forKey:@"objectValue"];
                                [subview1 setTitle:[dictLanguage objectForKey:@"filter.select-description"] forState:UIControlStateNormal];
                            }
                            else if (subview1.tag == filter_room) {
                                [dict setObject:[dictLanguage objectForKey:@"filter.select-room"] forKey:@"objectValue"];
                                [subview1 setTitle:[dictLanguage objectForKey:@"filter.select-room"] forState:UIControlStateNormal];
                            }
                        }
                    }
                }
            }
            else if ([unitId isEqualToString:@"0"]) {
                //get all object in tableview and set value
                for (int i=0;i < [mainArray count];i++) {
                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                    UITableViewCell *cell = [_mainTableView cellForRowAtIndexPath:indexPath];
                    
                    //loop to reset select unit
                    for (UIButton *subview1 in cell.contentView.subviews) {
                        NSMutableDictionary *dict = [mainArray objectAtIndex:i];
                        
                        if ([subview1 isKindOfClass:[UIButton class]]) {
                            if (subview1.tag == filter_unit){
                                [dict setObject:[dictLanguage objectForKey:@"filter.select-unit"] forKey:@"objectValue"];
                                [subview1 setTitle:[dictLanguage objectForKey:@"filter.select-unit"] forState:UIControlStateNormal];
                            }
                            else if (subview1.tag == filter_building) {
                                if ([[dict objectForKey:@"objectValue"] isEqualToString:[dictLanguage objectForKey:@"filter.select-building.other"]]) {
                                    //do nothing
                                }
                                else {
                                    [dict setObject:[dictLanguage objectForKey:@"filter.select-building"] forKey:@"objectValue"];
                                    [subview1 setTitle:[dictLanguage objectForKey:@"filter.select-building"] forState:UIControlStateNormal];
                                }
                            }
                            else if (subview1.tag == filter_floor) {
                                [dict setObject:[dictLanguage objectForKey:@"filter.select-floor"] forKey:@"objectValue"];
                                [subview1 setTitle:[dictLanguage objectForKey:@"filter.select-floor"] forState:UIControlStateNormal];
                            }
                            else if (subview1.tag == filter_system) {
                                [dict setObject:[dictLanguage objectForKey:@"filter.select-system"] forKey:@"objectValue"];
                                [subview1 setTitle:[dictLanguage objectForKey:@"filter.select-system"] forState:UIControlStateNormal];
                            }
                            else if (subview1.tag == filter_description) {
                                [dict setObject:[dictLanguage objectForKey:@"filter.select-description"] forKey:@"objectValue"];
                                [subview1 setTitle:[dictLanguage objectForKey:@"filter.select-description"] forState:UIControlStateNormal];
                            }
                            else if (subview1.tag == filter_room) {
                                [dict setObject:[dictLanguage objectForKey:@"filter.select-room"] forKey:@"objectValue"];
                                [subview1 setTitle:[dictLanguage objectForKey:@"filter.select-room"] forState:UIControlStateNormal];
                            }
                        }
                    }
                }
            }
            else if ([floorId isEqualToString:@"0"]) {
                //get all object in tableview and set value
                for (int i=0;i < [mainArray count];i++) {
                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                    UITableViewCell *cell = [_mainTableView cellForRowAtIndexPath:indexPath];
                    
                    //loop to reset select floor
                    for (UIButton *subview1 in cell.contentView.subviews) {
                        NSMutableDictionary *dict = [mainArray objectAtIndex:i];
                        
                        if ([subview1 isKindOfClass:[UIButton class]]) {
                            if (subview1.tag == filter_floor){
                                [dict setObject:[dictLanguage objectForKey:@"filter.select-floor"] forKey:@"objectValue"];
                                [subview1 setTitle:[dictLanguage objectForKey:@"filter.select-floor"] forState:UIControlStateNormal];
                            }
                            else if (subview1.tag == filter_room) {
                                [dict setObject:[dictLanguage objectForKey:@"filter.select-room"] forKey:@"objectValue"];
                                [subview1 setTitle:[dictLanguage objectForKey:@"filter.select-room"] forState:UIControlStateNormal];
                            }
                        }
                    }
                }
            }
            else if ([descriptionId isEqualToString:@"0"]) {
                //get all object in tableview and set value
                for (int i=0;i < [mainArray count];i++) {
                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                    UITableViewCell *cell = [_mainTableView cellForRowAtIndexPath:indexPath];
                    
                    //loop to reset select description
                    for (UIButton *subview1 in cell.contentView.subviews) {
                        NSMutableDictionary *dict = [mainArray objectAtIndex:i];
                        
                        if ([subview1 isKindOfClass:[UIButton class]]) {
                            if (subview1.tag == filter_description){
                                [dict setObject:[dictLanguage objectForKey:@"filter.select-description"] forKey:@"objectValue"];
                                [subview1 setTitle:[dictLanguage objectForKey:@"filter.select-description"] forState:UIControlStateNormal];
                            }
                        }
                    }
                }
            }
        }
    }
}

#pragma mark DatePickerViewDelegate
- (void) didCancelSectDatePicker {
    //do anything
    [popoverController dismissPopoverAnimated:YES];
}

- (void) didSelectDatePicker:(NSDate *)date paramSender:(id)sender {
    [popoverController dismissPopoverAnimated:YES];
    
    UIButton *btnDate = (UIButton*)sender;
    
    //convert to MMM dd, yyyy
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MMM dd, yyyy"];
    
    [btnDate setTitle:[dateFormatter stringFromDate:date] forState:UIControlStateNormal];
    
    //save value into dictionary
    //get all object in tableview and set value
    for (int i=0;i < [mainArray count];i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
        UITableViewCell *cell = [_mainTableView cellForRowAtIndexPath:indexPath];
        
        for (UIButton *subview in cell.contentView.subviews) {
            if ([subview isKindOfClass:[UIButton class]]) {
                if (subview == sender){
                    //get dictionary of this row
                    NSMutableDictionary *dict = [mainArray objectAtIndex:i];
                    [dict setObject:[dateFormatter stringFromDate:date] forKey:@"objectValue"];
                    break;
                }
            }
        }
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [mainArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    // Configure the cell...
    NSMutableDictionary *dict = [mainArray objectAtIndex:indexPath.row];
    
    UILabel *lbTitle = [[UILabel alloc] initWithFrame:CGRectMake(170, 5, 350, 21)];
    lbTitle.backgroundColor = [UIColor clearColor];
    lbTitle.text = [dict objectForKey:@"labelTitle"];
    lbTitle.textColor = [UIColor darkGrayColor];
    [cell.contentView addSubview:lbTitle];
    
    int objectType = [[dict objectForKey:@"objectType"] intValue];
    
    if (itemType == Building_Type) {
        switch (objectType) {
            case b_room_name:
            case b_square_metres:
            case b_construction_cost:
            case b_age:
            case b_cost_incurred_previous_year:
            case b_cost_incurred_current_year:
            case b_demolition_reason:
            {
                UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(495, 5, 354, 30)];
                textField.borderStyle  = UITextBorderStyleLine;
                textField.textColor = [UIColor darkGrayColor];
                textField.delegate = self;
                textField.layer.borderColor = [UIColor lightGrayColor].CGColor;
                textField.layer.borderWidth = 1;
                textField.tag = objectType;
                textField.text = [NSString stringWithFormat:@"%@",[dict objectForKey:@"objectValue"]];
                [cell.contentView addSubview:textField];
                
                //add temporary view to create edge insect for text in text field
                UIView *tmpView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 30)];
                tmpView.backgroundColor = [UIColor clearColor];
                
                textField.leftView = tmpView;
                textField.leftViewMode = UITextFieldViewModeAlways;
                
                textField.returnKeyType = UIReturnKeyNext;
                if (objectType == b_demolition_reason)
                    textField.returnKeyType = UIReturnKeyDone;
                else if (objectType == b_construction_cost || objectType == b_age || objectType == b_square_metres)
                    textField.keyboardType = UIKeyboardTypeNumberPad;
                else if (objectType == b_cost_incurred_previous_year || objectType == b_cost_incurred_current_year) {
                    cell.userInteractionEnabled = NO;
                }
                break;
            }
            case b_warranty_date_exp:
            case b_date_of_completion:
            case b_date_of_demolition:
            {
                //calendar
                UIButton *btnCombo = [UIButton buttonWithType:UIButtonTypeCustom];
                btnCombo.tag = objectType;
                btnCombo.frame = CGRectMake(495, 5, 354, 30);
                [btnCombo setBackgroundImage:[AppDelegate imageFromColor:[UIColor whiteColor]] forState:UIControlStateNormal];
                [btnCombo setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
                [btnCombo setBackgroundImage:[AppDelegate imageFromColor:APPLE_BLUE_COLOR] forState:UIControlStateHighlighted];
                
                [btnCombo setTitle:[dict objectForKey:@"objectValue"] forState:UIControlStateNormal];
                [btnCombo setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
                
                [btnCombo setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
                [btnCombo setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
                
                btnCombo.layer.borderColor = [UIColor lightGrayColor].CGColor;
                btnCombo.layer.borderWidth = 1.0;
                
                //add event handling for select date picker
                [btnCombo addTarget:self action:@selector(selectDate:) forControlEvents:UIControlEventTouchUpInside];
                
                //add drop down image to end of button
                UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"btnCalendar.png"]];
                imgView.frame = CGRectMake(310, -8, 44, 44);
                
                [btnCombo addSubview:imgView];
                [cell.contentView addSubview:btnCombo];
                break;
            }
            default:
            {
                UIButton *btnCombo = [UIButton buttonWithType:UIButtonTypeCustom];
                btnCombo.frame = CGRectMake(495, 5, 354, 30);
                [btnCombo setBackgroundImage:[AppDelegate imageFromColor:[UIColor whiteColor]] forState:UIControlStateNormal];
                [btnCombo setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
                [btnCombo setBackgroundImage:[AppDelegate imageFromColor:APPLE_BLUE_COLOR] forState:UIControlStateHighlighted];
                
                [btnCombo setTitle:[dict objectForKey:@"objectValue"] forState:UIControlStateNormal];
                [btnCombo setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
                
                [btnCombo setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
                [btnCombo setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
                
                btnCombo.layer.borderColor = [UIColor lightGrayColor].CGColor;
                btnCombo.layer.borderWidth = 1.0;
                
                //get objectType and assign for button's tag
                btnCombo.tag = objectType;
                
                [btnCombo addTarget:self action:@selector(selectComboBox:) forControlEvents:UIControlEventTouchUpInside];
                
                //add drop down image to end of button
                UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iconDropDown.png"]];
                imgView.frame = CGRectMake(330, 11, 13, 8);
                
                [btnCombo addSubview:imgView];
                [cell.contentView addSubview:btnCombo];
                
                if (objectType == filter_floor && [[dict objectForKey:@"objectValue"] isEqualToString:@"0"])
                    [btnCombo setTitle:[dictLanguage objectForKey:@"filter.select-floor"] forState:UIControlStateNormal];
                else if (objectType == filter_room && [[dict objectForKey:@"objectValue"] isEqualToString:@"0"])
                    [btnCombo setTitle:[dictLanguage objectForKey:@"filter.select-room"] forState:UIControlStateNormal];
                break;
            }
        }
    }
    else {
        switch (objectType) {
            case f_equipment_id:
            case f_brand:
            case f_serial_no:
            case f_make_model:
            case f_capacity:
            case f_manufacture_detail:
            case f_agent_detail:
            case f_capital_cost:
            case f_age:
            case f_amp_frequency:
            case f_amp_budciet:
            case f_cost_incurred_previous_year:
            case f_cost_incurred_current_year:
            case f_condemnation_reason:
            {
                UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(495, 5, 354, 30)];
                textField.borderStyle  = UITextBorderStyleLine;
                textField.textColor = [UIColor darkGrayColor];
                textField.delegate = self;
                textField.layer.borderColor = [UIColor lightGrayColor].CGColor;
                textField.layer.borderWidth = 1;
                textField.tag = objectType;
                textField.text = [NSString stringWithFormat:@"%@",[dict objectForKey:@"objectValue"]];
                [cell.contentView addSubview:textField];
                
                //add temporary view to create edge insect for text in text field
                UIView *tmpView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 30)];
                tmpView.backgroundColor = [UIColor clearColor];
                
                textField.leftView = tmpView;
                textField.leftViewMode = UITextFieldViewModeAlways;
                
                textField.returnKeyType = UIReturnKeyNext;
                if (objectType == f_condemnation_reason)
                    textField.returnKeyType = UIReturnKeyDone;
                else if (objectType == f_age || objectType == f_capacity || objectType == f_capital_cost)
                    textField.keyboardType = UIKeyboardTypeNumberPad;
                else if (objectType == f_cost_incurred_previous_year || objectType == f_cost_incurred_current_year) {
                    cell.userInteractionEnabled = NO;
                }
                break;
            }
            case f_expiry_date:
            case f_date_of_installation:
            case f_date_of_condemnation:
            {
                //calendar
                UIButton *btnCombo = [UIButton buttonWithType:UIButtonTypeCustom];
                btnCombo.tag = objectType;
                btnCombo.frame = CGRectMake(495, 5, 354, 30);
                [btnCombo setBackgroundImage:[AppDelegate imageFromColor:[UIColor whiteColor]] forState:UIControlStateNormal];
                [btnCombo setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
                [btnCombo setBackgroundImage:[AppDelegate imageFromColor:APPLE_BLUE_COLOR] forState:UIControlStateHighlighted];
                
                NSString *objectValue = [dict objectForKey:@"objectValue"] == nil ? @"" : [dict objectForKey:@"objectValue"];
                [btnCombo setTitle:[NSString stringWithFormat:@"%@",objectValue] forState:UIControlStateNormal];
                [btnCombo setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
                
                [btnCombo setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
                [btnCombo setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
                
                btnCombo.layer.borderColor = [UIColor lightGrayColor].CGColor;
                btnCombo.layer.borderWidth = 1.0;
                
                //add event handling for select date picker
                [btnCombo addTarget:self action:@selector(selectDate:) forControlEvents:UIControlEventTouchUpInside];
                
                //add drop down image to end of button
                UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"btnCalendar.png"]];
                imgView.frame = CGRectMake(310, -8, 44, 44);
                
                [btnCombo addSubview:imgView];
                [cell.contentView addSubview:btnCombo];
                break;
            }
            default:
            {
                UIButton *btnCombo = [UIButton buttonWithType:UIButtonTypeCustom];
                btnCombo.frame = CGRectMake(495, 5, 354, 30);
                [btnCombo setBackgroundImage:[AppDelegate imageFromColor:[UIColor whiteColor]] forState:UIControlStateNormal];
                [btnCombo setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
                [btnCombo setBackgroundImage:[AppDelegate imageFromColor:APPLE_BLUE_COLOR] forState:UIControlStateHighlighted];
                
                [btnCombo setTitle:[dict objectForKey:@"objectValue"] forState:UIControlStateNormal];
                [btnCombo setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
                
                [btnCombo setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
                [btnCombo setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
                
                btnCombo.layer.borderColor = [UIColor lightGrayColor].CGColor;
                btnCombo.layer.borderWidth = 1.0;
                
                //get objectType and assign for button's tag
                btnCombo.tag = objectType;
                
                [btnCombo addTarget:self action:@selector(selectComboBox:) forControlEvents:UIControlEventTouchUpInside];
                
                //add drop down image to end of button
                UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iconDropDown.png"]];
                imgView.frame = CGRectMake(330, 11, 13, 8);
                
                [btnCombo addSubview:imgView];
                [cell.contentView addSubview:btnCombo];
                
                if (objectType == filter_floor && [[dict objectForKey:@"objectValue"] isEqualToString:@"0"])
                    [btnCombo setTitle:[dictLanguage objectForKey:@"filter.select-floor"] forState:UIControlStateNormal];
                else if (objectType == filter_room && [[dict objectForKey:@"objectValue"] isEqualToString:@"0"])
                    [btnCombo setTitle:[dictLanguage objectForKey:@"filter.select-room"] forState:UIControlStateNormal];
                break;
            }
        }
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark UITextFieldDelegate 
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    myTextField = textField;
    return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    //get all object in tableview and set value
//    for (int i=0;i < [mainArray count];i++) {
//        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
//        UITableViewCell *cell = [_mainTableView cellForRowAtIndexPath:indexPath];
//        
//        for (UITextField *subview in cell.contentView.subviews) {
//            if ([subview isKindOfClass:[UITextField class]]) {
//                if (subview.tag == textField.tag){
//                    //set content offset to this cell
//                    [_mainScrollView setContentOffset:CGPointMake(_mainScrollView.frame.origin.x,i*_mainTableView.rowHeight)];
//                    break;
//                }
//            }
//        }
//    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    switch (textField.tag) {
        case b_square_metres:
        case b_age:
        case b_construction_cost:
        case f_capital_cost:
        case f_age:
        case f_capacity:
        {
            NSString *textNumber = @"[a-zA-Z!()&$@,;?':/-]";
            if (![string isEqualToString:@""] && [string isMatchedByRegex:textNumber]) {
                UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"]
                                                                 message:[dictLanguage objectForKey:@"building-mgmt.add-room.input-number-require"]
                                                                delegate:nil
                                                       cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"]
                                                       otherButtonTitles:nil];
                [dialog show];
                [textField resignFirstResponder];
                return NO;
            }
            break;
        }
        default:
            break;
    }
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    //get all object in tableview and set value
    for (int i=0;i < [mainArray count];i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
        UITableViewCell *cell = [_mainTableView cellForRowAtIndexPath:indexPath];
        
        for (UITextField *subview in cell.contentView.subviews) {
            if ([subview isKindOfClass:[UITextField class]]) {
                if (subview.tag == textField.tag){
                    //get dictionary of this row
                    NSMutableDictionary *dict = [mainArray objectAtIndex:i];
                    [dict setObject:textField.text forKey:@"objectValue"];
                    break;
                }
            }
        }
    }
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    int maxField = itemType == Building_Type ? b_demolition_reason : f_condemnation_reason;
    if (textField.tag == maxField)
        [textField resignFirstResponder];
    else {
        UITextField *txt;
        BOOL isOK = NO;
        for (int i=0;i < [mainArray count];i++) {
            //get next row and set become responder for the next field
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i+1 inSection:0];
            UITableViewCell *cell = [_mainTableView cellForRowAtIndexPath:indexPath];
            
            for (UITextField *subview in cell.contentView.subviews) {
                if ([subview isKindOfClass:[UITextField class]]) {
                    if (subview.tag == b_cost_incurred_current_year || subview.tag == b_cost_incurred_previous_year || subview.tag == f_cost_incurred_current_year || subview.tag == f_cost_incurred_previous_year)
                        continue;
                    if (subview.tag > textField.tag){
                        isOK = YES;
                        txt = subview;
                        break;
                    }
                }
            }
            if (isOK){
                [txt becomeFirstResponder];
                break;
            }
        }
    }
    return YES;
}

@end
